package com.zkca.xf.ui.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.trello.rxlifecycle2.components.support.RxFragment;
import com.zkca.xf.ConstantsXF;
import com.zkca.xf.Constants_SP;
import com.zkca.xf.R;
import com.zkca.xf.model.javabean.UserBean_W;
import com.zkca.xf.model.javabean.uploadbean.RequestUser;
import com.zkca.xf.presenter.LogOutPersenter;
import com.zkca.xf.ui.activity.Activity_Login_Code;
import com.zkca.xf.ui.activity.me.FeedbackActivity;
import com.zkca.xf.ui.activity.me.PersonalDetailsActivity;
import com.zkca.xf.ui.activity.me.SettingActivity;
import com.zkca.xf.ui.adapter.SingleAdapter;
import com.zkca.xf.ui.adapter.ViewHolder;
import com.zkca.xf.utils.Md5Util;
import com.zkca.xf.utils.SPUtil;
import com.zkca.xf.utils.TimeUtils;
import com.zkca.xf.utils.ToastUtils;
import com.zkca.xf.view.LogoutView;

import java.util.Arrays;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.functions.Consumer;


/**
 * Created by pc on 2018/8/6.
 * 我的
 */

public class MeFragment extends RxFragment implements  View.OnClickListener ,LogoutView{

    CircleImageView myHead;
    TextView tv_quit;
    TextView tvName;
    TextView tvAddress;
    private View meView;
    protected Context mContext;
    private View headerView;
    private XRecyclerView xrv_me;
    private LinearLayoutManager linearLayoutManager;
    private SingleAdapter<String> adapter;
    private List<String> dataMeList;
    private int[] my_icon = {R.mipmap.dgrxx, R.mipmap.setting, R.mipmap.dwt, R.mipmap.jianchagengxin, R.mipmap.lianxikefu};
    String[] permissions = {Manifest.permission.CALL_PHONE};
    private String userName, orgName, userHead;
    private SPUtil sp;

    private RequestUser requestUser;
    private LogOutPersenter logOutPersenter;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        meView = inflater.inflate(R.layout.fragment_me, container, false);
        logOutPersenter=new LogOutPersenter(this,this);
        initView();
        // unbinder = ButterKnife.bind(this, meView);
        initdata();
        return meView;
    }

    private void initRequsUserData() {
        requestUser = new RequestUser();
        requestUser.setAccessId(SPUtil.getString(getContext(),Constants_SP.ACCESSID));
        requestUser.setAuthCode("000000");
        requestUser.setTimeStamp(TimeUtils.getTime());
        requestUser.setMobileType(1);

        //requestUser.setMobileToken(mobileToken);
        requestUser.setSign(generateSign(requestUser));

        logOutPersenter.Logout(requestUser);
    }

    private String generateSign(RequestUser req) {
        String result = null;
        StringBuilder sb = new StringBuilder(new StringBuffer(req.getAuthCode()).reverse().toString());
        sb.append("#FF00");
        sb.append(ConstantsXF.APIKEY);
        sb.append("#DCF0");
        sb.append(req.getAccessId());
        sb.append("#0FCD");
        sb.append(req.getTimeStamp());
        sb.append("#0000");
        sb.append(req.getAuthCode());
        sb.append("#00FF");
        result = sb.toString();
        for (int k = 0; k < ConstantsXF.APICOUNT; k++) {
            result = Md5Util.md5Sum(result);
        }
        return result;
    }
    private void initdata() {

        String userName =  SPUtil.getString(getContext(),Constants_SP.USERNAME, "");
        String orgName = SPUtil.getString(getContext(),Constants_SP.UNITNAME, "");
        String userHead = SPUtil.getString(getContext(),Constants_SP.USER_HEAD, "");
        tvName.setText(userName);
        tvAddress.setText(orgName);
        //Glide.with(this).load(ConstantsXF.URL_SERVER + userHead).into(myHead);
    }

    private void initView() {
        xrv_me = (XRecyclerView) meView.findViewById(R.id.xrv_me);
        tv_quit= (TextView) meView.findViewById(R.id.tv_quit);
        headerView = LayoutInflater.from(mContext).inflate(R.layout.header_me, null, false);
        linearLayoutManager = new LinearLayoutManager(mContext);
        tv_quit.setOnClickListener(this);
        xrv_me.setLayoutManager(linearLayoutManager);
        xrv_me.addHeaderView(headerView);
        xrv_me.setLoadingMoreEnabled(false);
        xrv_me.setPullRefreshEnabled(false);

        myHead = headerView.findViewById(R.id.my_head);
        tvName = headerView.findViewById(R.id.tv_name);
        tvAddress = headerView.findViewById(R.id.tv_address);

        dataMeList = Arrays.asList(getResources().getStringArray(R.array.my_list));
        adapter = new SingleAdapter<String>(mContext, dataMeList, R.layout.me_item) {
            @Override
            public void convert(ViewHolder holder, String data, final int position) {
                TextView tv_title = holder.getView(R.id.tv_title);
                final ImageView my_image = holder.getView(R.id.iv_my_image);
                tv_title.setText(data);
                my_image.setImageDrawable(getResources().getDrawable(my_icon[position]));

                holder.setItemViewOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        switch (position) {
                            case 0://个人信息
                                intent.setClass(mContext, PersonalDetailsActivity.class);
                                startActivity(intent);
                                break;
                            case 1://设置
                                intent.setClass(mContext, SettingActivity.class);
                                startActivity(intent);
                                break;
//                            case 2://问题反馈
//                                intent.setClass(mContext, FeedbackActivity.class);
//                                startActivity(intent);
//                                break;
                            case 2://检查更新
                                ToastUtils.show(mContext,"当前已是最新版本");
                                break;
                            case 3://联系客服
                                getNotescontact();
                                break;
                        }
                    }
                });
            }
        };
        xrv_me.setAdapter(adapter);
    }



    //联系客服
    private void getNotescontact() {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(mContext);
        normalDialog.setTitle("联系客服");
        normalDialog.setMessage("客服电话：15811539561");
        normalDialog.setPositiveButton("拨打",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        final Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:15811539561"));
                        if (mContext instanceof Activity) {
                            Activity mActivity = (Activity) mContext;
                            RxPermissions rxPermissions = new RxPermissions(mActivity);
                            rxPermissions.request(permissions)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(@NonNull Boolean granted) throws Exception {
                                            //同意授权
                                            if (granted) {
                                                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                                    ToastUtils.show(mContext, "请添加手机拨打电话权限");
                                                    return;
                                                }
                                                startActivity(intent);
                                            } else {//拒绝
                                                ToastUtils.show(mContext, "请添加手机拨打电话权限");
                                            }
                                        }
                                    });

                        }
                    }
                });
        normalDialog.setNegativeButton("返回",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        // 显示
        normalDialog.show();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_quit:

                SPUtil.putString(mContext,Constants_SP.USER_ID, "");
                SPUtil.putString(mContext,Constants_SP.ORG_ID, "");

                SPUtil.putInt(mContext,Constants_SP.DEPID, -199);
                Intent intent=new Intent();
                intent.setClass(mContext,Activity_Login_Code.class);
                mContext.startActivity(intent);
                if (mContext instanceof Activity) {
                    Activity mActivity = (Activity) mContext;
                    mActivity.finish();
                }
                initRequsUserData();
                break;
        }
    }

    @Override
    public void showProgressDialog() {

    }

    @Override
    public void hideProgressDialog() {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void Logout(UserBean_W usermesager) {

    }
}
